package com.cgnpc.scp.common.config;

import com.cgnpc.scp.common.bean.CustomDownloadFileResourceHttpMessageConverter;
import com.cgnpc.scp.common.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.File;
import java.net.URL;
import java.util.UUID;

/**
 * 定制的SpringConfig类<br>
 */
@Configuration
public class CustomSpringConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomSpringConfig.class);

    private static final File FILE_INSIDE_TEMP_DIR = getInsideTempDir();

    @Bean
    public CustomDownloadFileResourceHttpMessageConverter createCustomDownloadFileResourceHttpMessageConverter() {
        return new CustomDownloadFileResourceHttpMessageConverter();
    }

    /**
     * 获取内部的临时文件夹，暂定"classpath:___insideTempDir"
     *
     * @return file
     */
    public static File getInsideTempDir() {
        if (FILE_INSIDE_TEMP_DIR != null) {
            return FILE_INSIDE_TEMP_DIR;
        }

        final String logInfo = "[CustomSpringConfig_getInsideTempDir_UUID_" + UUID.randomUUID().toString() + "]";

        try {
            LOGGER.info("{}init;makeDir.to.classpath:___insideTempDir;", logInfo);
            ClassLoader classLoader = CustomSpringConfig.class.getClassLoader();
            URL url = classLoader.getResource("");
            File fileInsideTempDir = new File(new File(url.toURI()), "___insideTempDir");
            LOGGER.info("{}fileInsideTempDir:{};", logInfo, fileInsideTempDir);
            FileUtil.mkdirs(fileInsideTempDir);
            return fileInsideTempDir;
        } catch (Exception e) {
            LOGGER.error("{}error", logInfo, e);
            throw new RuntimeException(e);
        }
    }

}
